﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;

namespace Nirvana
{
    [RequireComponent(typeof(Dropdown))]
    [AddComponentMenu("Nirvana/UI/Bind/Variable Bind Dropdown")]
    public sealed class UIVariableBindDrapdown : UIVariableBind
    {
        private static Logger logger = LogSystem.GetLogger("UIVariableBindDrapdown");
        [SerializeField]
        [VariableName(UIVariableType.Integer)]
        private string valueBind;
        private Dropdown _dropdown;
        private UIVariable _uivariable;

        private void Awake()
        {
            this.Binds();
            this._dropdown = base.GetComponent<Dropdown>();
            if (this._dropdown == null)
            {
                return;
            }
        }


        protected override void BindVariables()
        {
            Assert.IsNull<UIVariable>(this._uivariable);
            if (!string.IsNullOrEmpty(this.valueBind))
            {
                this._uivariable = base.FindVariable(this.valueBind);
                if (this._uivariable == null)
                {
                    logger.LogWarning("{0} can not find a variable {1}", base.name, this.valueBind);
                }
                else
                {
                    this._uivariable.OnValueInitialized += this.UpdateDrop;
                    this._uivariable.OnValueChanged += this.UpdateDrop;
                    this._uivariable.Add(this);
                    this.UpdateDrop();
                }
            }
        }

        protected override void UnbindVariables()
        {
            if (this._uivariable != null)
            {
                this._uivariable.OnValueInitialized -= this.UpdateDrop;
                this._uivariable.OnValueChanged -= this.UpdateDrop;
                this._uivariable.Remove(this);
                this._uivariable = null;
            }
        }

        private  void UpdateDrop()
        {
            if (this._dropdown == null)
            {
                this._dropdown = base.GetComponent<Dropdown>();
            }
            if (this._dropdown != null)
            {
                int integer = this._uivariable.GetInteger();
                this._dropdown.value = integer;
            }
        }
    }
}

